package com.deer.wms.ware.task.web;

import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.constant.InventoryConstant;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.Inventory.InventoryTransact;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.inventory.service.InventoryTransactService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.util.BeanUtils;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.review.manage.model.BillRecord;
import com.deer.wms.review.manage.service.BillRecordService;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.ware.task.model.Return.*;
import com.deer.wms.ware.task.service.ReturnDetailService;
import com.deer.wms.ware.task.service.ReturnMasterService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * Created by ll on 2020/03/13.
 */
@Api(description = "退货单信息api接口")
@RestController
@RequestMapping("/return/masters")
public class ReturnMasterController {

    @Autowired
    private ReturnMasterService returnMasterService;

    @Autowired
    private CaseMasterService caseMasterService;

    @Autowired
    private BillRecordService billRecordService;

    @Autowired
    private ReturnDetailService returnDetailService;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private InventoryTransactService inventoryTransactService;

    @PostMapping
    public Result add(@RequestBody ReturnMaster returnMaster) {
        returnMasterService.save(returnMaster);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "新增退货信息", notes = "新增退货信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/insert")
    public Result insert(@RequestBody ReturnData returnData, @ApiIgnore @User CurrentUser currentUser) {
        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        returnMasterService.create(returnData,currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        returnMasterService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }
    @GetMapping("/detail")
    public Result detail(Integer id) {
        ReturnMaster returnMaster = returnMasterService.getById(id);
        return ResultGenerator.genSuccessResult(returnMaster);
    }

    @GetMapping("/list")
    public Result list(ReturnMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<ReturnMaster> list = returnMasterService.list();
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @ApiOperation(value = "审核", notes = "审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/review")
    public Result review(String billNo, Integer reviewResult,Integer caseDetailId,String memo, @ApiIgnore @User CurrentUser currentUser) {
        ReturnMaster returnMaster = returnMasterService.findBy("bill_no", billNo);
        //-1不通过   0-流转中  1-通过  2-初始化
        Integer lastReviewResult = caseMasterService.review(caseDetailId,currentUser.getUserId(),reviewResult,memo);


        if (lastReviewResult == -1) {
            returnMaster.setState(-1);
            returnMasterService.updateById(returnMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,49);//退货审核
            billRecord.setResult("退回");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        } else if (lastReviewResult == 0) {
            returnMaster.setState(0);
            returnMasterService.updateById(returnMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,49);//退货审核
            billRecord.setResult("流转");
            billRecordService.updateById(billRecord);
        }else if (lastReviewResult == 2) {
            returnMaster.setState(2);
            returnMasterService.updateById(returnMaster);
        } else if (lastReviewResult == 1) {
            returnMaster.setState(1);
            returnMasterService.updateById(returnMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,49);//退货审核
            billRecord.setResult("通过");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        }
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "重新发起审核", notes = "重新发起审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/reReview")
    public Result reReview(String billNo, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        ReturnMaster returnMaster = returnMasterService.findBy("bill_no", billNo);

        //初始化状态 2
        returnMaster.setState(2);
        returnMasterService.updateById(returnMaster);
        caseMasterService.createCase(billNo, 8, currentUser.getUserId(), returnMaster.getWareId(),returnMaster.getOrganizationId());

        return ResultGenerator.genSuccessResult();
    }
    @ApiOperation(value = "增删退货单", notes = "增删增删退货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/update")
    public Result update(@RequestBody ReturnData returnData, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        BillRecord billRecord =new BillRecord();
        billRecord.setBillNo(returnData.getReturnMaster().getBillNo());
        billRecord.setRecordType(50);//退货修改
        billRecord.setCreateTime(DateUtils.getNowDateTimeString());
        billRecord.setCreateUserId(currentUser.getUserId());
        billRecord.setCreateUserName(currentUser.getUserName());
        billRecordService.createBillRecord(billRecord,currentUser);
        ReturnMaster returnMaster = returnData.getReturnMaster();
        returnMasterService.updateById(returnMaster);

        List<ReturnDetail> returnDetails = returnData.getReturnDetails();

        for(int i=0;i<returnDetails.size();i++){
            ReturnDetail returnDetail = returnDetails.get(i);
            String detailNo = returnData.getReturnMaster().getBillNo() + "-" + (i+1);
            returnDetail.setDetailNo(detailNo);
            returnDetail.setBillNo(returnData.getReturnMaster().getBillNo());
            returnDetail.setDetailNo(detailNo);

            returnDetailService.updateById(returnDetail);
        }
        BillRecord billRecord1 =billRecordService.findByBillNoAndType(returnData.getReturnMaster().getBillNo(),50);//退货修改
        billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
        billRecord1.setModifyUserId(currentUser.getUserId());
        billRecord1.setModifyUserName(currentUser.getUserName());
        billRecordService.updateById(billRecord1);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "批量退货", notes = "批量退货")
    @PostMapping("/return")
    public Result delivery(@RequestBody ReturnDetailData returnDetailData,@User CurrentUser user) {
        for (ReturnDetail returnDetail: returnDetailData.getReturnDetails()) {
            Integer inventoryId = returnDetail.getInventoryId();
            String billNo = returnDetail.getBillNo();
            ReturnMaster returnMaster = returnMasterService.findBy("bill_no",billNo);

            Inventory fromIv = inventoryService.getById(inventoryId);
            Inventory toIv = new Inventory();
            BeanUtils.copyProperties(fromIv, toIv);
            toIv.setOrganizationId(returnMaster.getOrganizationId());
            toIv.setOrganizationName(returnMaster.getOrganizationName());
//            inventoryTransactService.run(fromIv, toIv, InventoryConstant.INVENTORY_TRANS_ORG, returnDetail.getDetailNo(), user.getUserId(), user.getUserName(), null);

        }

        return ResultGenerator.genSuccessResult();
    }

}
